var Fiber = require('fibers');
var myfs = require("./_include/fs");
var jslist = myfs.ls(__dirname + "/RESTAPI");
var ResponObj = require("./_include/responObj");
var domain = require("domain");
RESTlist = jslist.filter(function(fileName) {
	var suffix = ".rest.js"
	return fileName.toLowerCase().substr(-suffix.length) == suffix;
});
module.exports = function setRouter(app) {
	Fiber(function() {
		console.log("API初始化中……");
		console.time("API初始化完成！");
		RESTlist.forEach(function(fileName) {
			try {
				var RESTModule = require(fileName);
			} catch (e) {
				console.error(fileName);
				throw e;
			}
			var prefix = RESTModule.prefix;
			// console.log("运行", fileName, "模块到：", prefix);
			if (RESTModule._init) {
				RESTModule._init(app);
				delete RESTModule._init;
			}
			delete RESTModule.prefix;
			var methodNames = Object.keys(RESTModule);
			methodNames.forEach(function(methodName) {
				if (methodName.indexOf("_") == 0) { //下划线开头的默认为私有，不处理
					return;
				}
				var methodSet = RESTModule[methodName];
				Object.keys(methodSet).forEach(function(extendURL) {

					var method = methodSet[extendURL];
					var handles = [function(req, res, next) {
						console.log('\n:> %s %s - %s', req.method, req.url, (new Date).format("HH:mm:ss yy-MM-dd"));
						// x-response-time 计算响应时间
						// logger 打印请求日志
						var start = new Date;
						var _body;
						var _send_ti;
						var _self = Object.create(req);
						var co_data = req.query.co_data;

						var d = domain.create();
						d.uuid = (+new Date).toString(36).substr(3);
						d.add(req);
						d.add(res);
						d.req = req;
						d.res = res;

						if (!co_data) {
							//常规模式
							_self.request = req;
							_self.response = res;
							_self.cookies = {
								set: function() {
									return res.cookie.apply(res, arguments);
								},
								get: function(name) {
									return req.cookies[name];
								}
							}

							_self.__defineGetter__("body", function() {
								return _body;
							});

							_self.__defineSetter__("body", function(v) {
								var ms = new Date - start;
								console.log('%s %s - %s', req.method, req.url, ms);
								if (_body) {
									console.log("Send Error:Can't set headers after they are sent.", _body, v);
									return;
								}
								_body = v;
								res.send(_body);
								d.exit();
							});
						} else {
							//jsonp模式
							try {
								co_data = JSON.parse(co_data);
							} catch (e) {
								console.error("co_data:", co_data)
							}
							// console.log(co_data);
							var _query = co_data.query;
							var _data = co_data.data;
							var _cookies = co_data.cookies;
							var _method = co_data.method.toLowerCase();
							method = (RESTModule[_method] || {})[extendURL];

							if (_method == "get") {
								for (var key in _data) {
									if (_data.hasOwnProperty(key)) {
										_query[key] = _data[key];
									}
								}
								_data = {};
							}
							req.query = _query;
							req.body = _data;

							_self.request = req;
							_self.response = res;
							_self.cookies = {
								_cookiesSet: [],
								set: function() {
									return res.cookie.apply(res, arguments);
									// _cookiesSet.push(Array.prototype.slice.call(arguments))
								},
								get: function(name) {
									return req.cookies[name];
								}
							}

							_self.__defineGetter__("body", function() {
								return _body;
							});

							_self.__defineSetter__("body", function(v) {
								var ms = new Date - start;
								console.log('%s %s - %s', req.method, _method, req.url, ms);
								_body = v;
								res.send("define(function(){return " + JSON.stringifySecurity(_body) + "})");
								d.exit();
							});
						}

						function _send_error(e) {
							console.log("--------------------\nError:", String(e), "\n", e.stack, "\n--------------------");
							_self.body = ResponObj("error", e);
						}
						d.on('error', _send_error);
						try {
							d.run(function() {
								Fiber(function() {
									method.call(_self, req, res, next);
								}).run();
							});
						} catch (e) {
							_send_error(e);
						}
						// next();//no next ，这已经是最后的环节了，否则会把异步回调给销毁
					}];
					if (method instanceof Array) {
						handles.unshift.apply(handles, method.splice(0, method.length - 1));
						method = method[method.length - 1];
					}
					handles.unshift(prefix + (extendURL === "/" ? "" : extendURL));
					//只格式化中文不格式化"/"
					handles[0] = encodeURI(handles[0]);
					app[methodName].apply(app, handles);

					if (methodName === "delete") {
						app.post(handles[0], function(req, res, next) {
							if (req.headers.fixdelete === 'delete') {
								return handles[1].apply(this, arguments);
							} else {
								next()
							}
						});
					}
					//已经JSONP的访问支持
					var json_prefix = "/jsonp" + handles[0];
					handles[0] = json_prefix;
					app.get.apply(app, handles);
				});
			});
		});
		console.timeEnd("API初始化完成！");
		app.use(function errorHandler(err, req, res, next) {
			// console.group("App Error:");
			console.log("App Error:");
			console.error(err.stack);
			// console.groupEnd();

			next();
		});
	}).run();
}